﻿using BCData.TMS.Driver;
using BCDto.Location.Driver;
using BCDto.TMS.Driver;
using BCMongoData.TMS.Location.Driver;
using BCMongoEntity.TMS.Location.Driver;
using BCService.Common.Area;
using BCService.Utils;
using MongoDB.Bson;
using System;
using System.Collections.Generic;

namespace BCService.TMS.Location.Driver
{
    public class DriverLocationService : IDriverLocationService
    {
        private readonly IDriverData driverData;
        private readonly IDriverLocationMongoData driverLocationMongoData;
        private readonly IZoneService zoneService;


        public DriverLocationService(IDriverData driverData, IDriverLocationMongoData driverLocationMongoData, IZoneService zoneService)
        {
            this.driverData = driverData;
            this.driverLocationMongoData = driverLocationMongoData;
            this.zoneService = zoneService;
        }

        public DriverLocationBsonDto SetLocation(DriverDto currentDriver, DriverLocationRequestDto dto)
        {
            var driver = driverData.GetDriverByIdAsync(currentDriver.DriverId).GetAwaiter().GetResult();
            if (driver == null)
            {
                throw new ArgumentException("当前司机不存在");
            }
            //校验省市区
            var zoneEntity = this.zoneService.GetFromZoneEntity(dto.ZoneCode);
            if (zoneEntity == null && zoneEntity.cityEntity == null && zoneEntity.countyEntity == null)
            {
                throw new ArgumentException("此区域信息不正确!");
            }
            DriverLocationEntity entity = currentDriver.As<DriverLocationEntity>();
            entity.Latitude = dto.Latitude;
            entity.Longitude = dto.Longitude;
            entity.CityCode = zoneEntity.cityEntity != null ? zoneEntity.cityEntity.CityCode : string.Empty;
            entity.CoutyCode = zoneEntity.countyEntity != null ? zoneEntity.countyEntity.CountyCode : string.Empty;
            entity.DailyReceivedOrders = currentDriver.DailyReceivedOrders;
            entity.TotalReceivedOrders = currentDriver.TotalReceivedOrders;
            entity.FullLoadRatio = currentDriver.FullLoadRatio;
            var result = this.driverLocationMongoData.Update(entity);
            return result.As<DriverLocationBsonDto>();
        }

        public IEnumerable<DriverLocationBsonDto> GetGeoNearLocationsByCoordinate(double[] location, double maxDistance, List<BsonElement> query, List<BsonElement> projections)
        {
            var result = driverLocationMongoData.GetGeoNearLocationsByCoordinate(location, maxDistance, query, projections);
            return result.As<IEnumerable<DriverLocationBsonDto>>();
        }

        public DriverLocationBsonDto GetDriverLocationInfo(string vehicleNo)
        {
            var result = driverLocationMongoData.GetDriverLocationInfo(vehicleNo).GetAwaiter().GetResult();
            return result.As<DriverLocationBsonDto>();
        }
    }
}
